<?php

namespace app\common\model;

use think\Db;
use think\Model;


class AgentStockRecord extends Model
{

    

    

    // 表名
    protected $name = 'agent_stock_record';
    
    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';

    // 定义时间戳字段名
    protected $createTime = 'create_time';
    protected $updateTime = 'update_time';
    protected $deleteTime = false;

    // 追加属性
    protected $append = [
		'type_text'
    ];
    

    const TYPE_IN = 1;
    const TYPE_OUT = 2;
    const TYPE_DESTRUCT = 3;
    
    public static $typeList = [
    	self::TYPE_IN => '收货入库',
	    self::TYPE_OUT => '出库发货',
	    self::TYPE_DESTRUCT => '核销'
    ];
    
    public function getTypeTextAttr($value, $data) {
    	$value = $value ? : $data['type'];
    	$list = self::$typeList;
    	return $list[$value] ?? '';
    }
    
	public function user() {
		return $this->belongsTo('user', 'user_id', 'id', '', 'left')->setEagerlyType(0);
	}
	
	
	public function goods() {
		return $this->belongsTo('goods', 'goods_id', 'id', '', 'left')->setEagerlyType(0);
	}
	
	public function spec() {
		return $this->belongsTo('goodsSpec', 'spec_id', 'id', '', 'left')->setEagerlyType(0);
	}
	
	/**
	 * 添加库存记录
	 * @param $userId 用户ID
	 * @param $goodsId 商品ID
	 * @param $specId 规格ID
	 * @param $type 类型
	 * @param $number 数量
	 * @param string $remark 备注
	 * @return int|string
	 */
	public function addRecord($userId, $goodsId, $specId, $type, $number, $remark = '') {
		
		return Db::name('agentStockRecord')->insert([
			'user_id' => $userId,
			'goods_id' => $goodsId,
			'spec_id' => $specId,
			'type' => $type,
			'number' => $number,
			'remark' => $remark,
			'create_time' => time()
		]);
	}
}
